<template>
  <div class="avatar">
    <div class="pic-area">
      <vueCropper ref="cropperRef" v-bind="option" @realTime="realTime"></vueCropper>
    </div>

    <div class="preview">
      <div class="title">预览图</div>
      <div class="pic-area" :style="clipPickInfo.div">
        <img :src="clipPickInfo.url" :style="clipPickInfo.img" alt="">
      </div>
    </div>

    <div class="btn-area">
      <!-- 只有label 的for 能关联input  如果用div/span 无效 -->
      <label class="btn" for="uploads">选择本地图片</label>
      <input type="file" id="uploads" style="display: none;" accept="image/png, image/jpeg, image/gif, image/jpg"
        @change="selectImg" />

      <el-button type="primary" size="large" class="btn confirm" @click="confirmPic">确定</el-button>
    </div>
  </div>
</template>

<script setup>
import 'vue-cropper/dist/index.css'
import { VueCropper } from "vue-cropper";
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { updateAvatar } from '@/api/myCenter/index.js'
import { useUserStore } from '@/store/index.js'

const userStore = useUserStore()//得到的state是reactive
const cropperRef = ref()
// https://www.npmjs.com/package/vue-cropper
const option = reactive({
  img: '',//裁剪图片的地址
  outputSize: 1,//图片质量
  outputType: 'jpeg',//裁剪生成图片的格式
  autoCrop: true,
  autoCropWidth: 230,  //默认生成截图框宽度
  autoCropHeight: 230, //默认生成截图框高度
  fixed: true,         //是否开启截图框宽高固定比例
  fixedNumber: [1, 1], //截图框的宽高比例
})
const clipPickInfo = ref({})

function realTime(data) {
  clipPickInfo.value = data
}

onMounted(() => {
  option.img = userStore.info.user_pic
})

function selectImg(e) {
  let file = e.target.files[0]
  if (!/.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
    ElMessage({
      message: '图片类型要求：jpeg、jpg、png',
      type: "error"
    });
    return
  }

  if (file.size > 1024 * 100) {
    ElMessage({
      message: '图片大小不要超过100K',
      type: 'error',
      duration: 5 * 1000
    })
    return
  }

  //转化为blob
  let reader = new FileReader()
  reader.onload = (e) => {
    let data
    if (typeof e.target.result === 'object') {
      // 把Array Buffer转化为blob 如果是base64不需要
      data = window.URL.createObjectURL(new Blob([e.target.result]))
    } else {
      data = e.target.result
    }
    option.img = data
  }
  // //转化为base64
  // reader.readAsDataURL(file)
  // 转化为blob
  reader.readAsArrayBuffer(file);
}

function confirmPic() {
  let _this = this;
  // 获取截图的 base64 数据
  cropperRef.value.getCropData(data => {
    console.log(data)
    updateAvatar({ avatar: data }).then(el => {
      if (el.code === 0) {
        ElMessage({
          message: '头像更新成功',
          type: 'success',
        })
      }
    })
  })
  //获取截图的blob数据  
  // post content-type:Multipart/form-data 不用写 会根据数据格式自动加content-type
  // cropperRef.value.getCropBlob(async (data) => {
  //   let formData = new FormData();
  //   formData.append('file', data, "DX.jpg")
  //   //调用axios上传
  //   let { data: res } = await _this.$http.post('/api/file/imgUpload', formData)
  //   if (res.code === 200) {
  //     _this.$message({
  //       message: res.msg,
  //       type: "success"
  //     });
  //     let data = res.data.replace('[', '').replace(']', '').split(',');
  //     let imgInfo = {
  //       name: _this.Name,
  //       url: data[0]
  //     };
  //     _this.$emit('uploadImgSuccess', imgInfo);
  //   } else {
  //     _this.$message({
  //       message: '文件服务异常，请联系管理员！',
  //       type: "error"
  //     });
  //   }
  // })
}
</script>

<style lang="scss" scoped>
.avatar {
  height: 100%;

  .pic-area {
    width: 600px;
    height: 600px;
  }

  .preview {
    position: fixed;
    top: 170px;
    left: 864px;

    .title {
      font-weight: bold;
      font-size: 25px;
      padding: 20px 0;
    }

    .pic-area {
      overflow: hidden;
      border: 1px solid #777777;
      background: #cccccc;
    }
  }

  .btn-area {
    margin: 20px 40px;

    .btn {
      width: fit-content;
      padding: 10px 20px;
      background: #5795e7;
      color: #fff;
      border-radius: 14px;
      font-size: 20px;
      cursor: pointer;

      &.confirm {
        margin-left: 40px;
        background-color: #ff4a4a;
      }
    }
  }
}
</style>